from exts import db
from datetime import datetime


class BlogModel(db.Model):
    __tablename__ = 'blog'
    # 博客id
    blog_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    # 作者id，外键
    blog_author_id = db.Column(db.String(32), db.ForeignKey('user.open_id'))
    # 标题
    title = db.Column(db.String(50), nullable=False)
    # 方面缩略图url
    cover_img = db.Column(db.String(100), nullable=False, default="http://127.0.0.1:5000/images/blog/default.jpg")
    # 内容，可变字符串类型
    content = db.Column(db.Text, nullable=False)
    # 创建时间
    create_time = db.Column(db.DateTime, nullable=False, default=datetime.now)
    # 修改时间
    update_time = db.Column(db.DateTime, nullable=False)
    # 审核状态 0:未通过 1:已通过 2:审核中
    allow_publish = db.Column(db.Integer, default=2)
    # 审核意见
    review = db.Column(db.String(200), default="")

    # 关系
    author = db.relationship('UserModel', back_populates='blogs')
    starlists = db.relationship('StarListModel', back_populates='blog', lazy='dynamic')
    comments = db.relationship('CommentModel', back_populates='blog', lazy='dynamic')

    def to_dict(self, choice='user'):
        blind = ('review', 'blog_author_id')
        simple = ('blog_id', 'cover_img', 'title', 'update_time')
        if choice == 'admin':
            return {c.name: self._convert_value(getattr(self, c.name, None)) for c in self.__table__.columns}
        elif choice == 'simple':
            return {c.name: self._convert_value(getattr(self, c.name, None)) for c in self.__table__.columns if c.name in simple}
        return {c.name: self._convert_value(getattr(self, c.name, None)) for c in self.__table__.columns if c.name not in blind}

    @staticmethod
    def _convert_value(value):
        if isinstance(value, datetime):
            return int(value.timestamp() * 1000)  # 转换为毫秒级时间戳
        return value